from flask import Request


def get_remote_address(request: Request) -> str:
    """获取客户端IP
    需要注意的是，使用此方法获取的客户IP地址必须在Http服务器（例如Nginx）中配置头信息，否则容易造成IP伪造。
    """
    ip_headers = [
        "X-Forwarded-For",
        "X-Real-IP",
        "Proxy-Client-IP",
        "WL-Proxy-Client-IP",
        "HTTP_CLIENT_IP",
        "HTTP_X_FORWARDED_FOR"
    ]
    for header in ip_headers:
        ip = request.headers.get(header)
        if is_unknown(ip) is False:
            return get_multistage_reverse_proxy_ip(ip)
    ip = request.remote_addr
    return get_multistage_reverse_proxy_ip(ip)


def is_unknown(check_string: str) -> bool:
    """检测给定字符串是否为未知，多用于检测HTTP请求相关
    check_string: 被检测的字符串
    """
    return check_string is None \
           or len(check_string.strip()) <= 0 \
           or check_string.lower() == 'unknown'


def get_multistage_reverse_proxy_ip(ip: str) -> str:
    """从多级反向代理中获得第一个非unknown IP地址
    ip: 获得的IP地址
    """
    if is_not_empty(ip) and ip.find(',') > 0:
        for sub_ip in ip.strip().split(','):
            if is_unknown(sub_ip) is False:
                ip = sub_ip
                break
    return ip


def is_empty(check_string: str) -> bool:
    """判断字符串是否为空字符串，以下情况均为空白字符串.
    1. None
    2. ''
    3. '     '
    """
    return check_string is None \
           or len(check_string) < 1 \
           or len(check_string.strip()) < 1 \
           or check_string.isspace()


def is_not_empty(check_string: str) -> bool:
    """判断字符串是否不为空字符串，is_empty反函数
    """
    return not is_empty(check_string)
